import { type RouteRecordRaw } from 'vue-router'
import { REDIRECT_HOME_PATH, LOGIN_ROUTER_NAME, ROUTE_WHITE_LIST } from '@/const/router'
import { basicRoutes } from '../routes/basic'
import { flatRoutes, initDynamicRouter } from './utils'
import useUserStore from '@/store/modules/user'
import useAuthStore from '@/store/modules/auth'
import type { Router } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({
  easing: 'ease',
  speed: 500, // 递增进度条的速度
  showSpinner: true, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3, // 初始化时的最小百分比
})

export function createRouterGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()
    const authStore = useAuthStore()
    console.log(userStore.token)

    document.title = to.meta.title as string
    NProgress.start()

    // 访问登录页面有token就在当前页面，没有token重定向到登录页面
    if (to.path === `/${LOGIN_ROUTER_NAME}`) {
      if (userStore.token) {
        return next(from.fullPath || REDIRECT_HOME_PATH)
      }

      resetRouter(router)
      return next()
    }

    const routeActions = [
      // 基础路由直接放行
      [() => basicRoutes.some((r) => r.path === to.path), () => next()],
      // 白名单路由直接放行
      [() => ROUTE_WHITE_LIST.includes(to.path), () => next()],
      // 未登录拦截
      [() => !userStore.token, () => next(`/${LOGIN_ROUTER_NAME}`)],
      // 整页路由处理
      [
        () => to.meta.fullPage,
        () => {
          to.matched = [to.matched[to.matched.length - 1]!]
          next()
        },
      ],
    ] as [() => boolean, () => void][]

    for (const [condition, action] of routeActions) {
      if (condition()) {
        return action()
      }
    }

    // 处理动态路由
    if (!authStore.authMenuList.length) {
      await initDynamicRouter()
      return next({ ...to, replace: true })
    }

    next()
  })

  router.afterEach(() => NProgress.done())

  router.onError((error) => {
    NProgress.done()
    console.error('路由错误：', error)
  })
}

export function resetRouter(router: Router) {
  const authStore = useAuthStore()
  const routes = flatRoutes(authStore.authMenuList as RouteRecordRaw[])
  routes.forEach((route) => {
    const { name } = route
    if (name && router.hasRoute(name)) router.removeRoute(name)
  })
}
